import {
	CheckCircleOutlined,
	CheckSquareOutlined,
	LockOutlined,
	MoonOutlined,
	SunOutlined,
	UserOutlined
} from "@ant-design/icons"
import { Button, Card, Form, Image, Input, Tooltip } from "antd"
import { Rule } from "antd/es/form"
import type { FC } from "react"
import { useDispatch, useSelector } from "react-redux"
import { useNavigate } from "react-router"
import styled from "styled-components"

import logo from "@/assets/svg-icon/logo.svg"
import { LoginParams } from "@/interface/user/login"
import { useLocale } from "@/locales"
import { getCurrencyInfoAsync, initAsync } from "@/stores/config/config.action"
import { globalStateType, setGlobalState, setLoad } from "@/stores/global/global.store"
import { getPermissionsAsync, loginAsync } from "@/stores/user/user.action"
import { md5ToString } from "@/utils/encrypt"

type FieldType = {
	username: string
	googleAuthCode: string
	merchantCode: string
	password: string
	type: number
}

type FormRules = {
	[key in keyof Omit<FieldType, "type">]: Rule[]
}

const Wrapper = styled.div`
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100vh;
	background-color: ${({ theme }) => (`${theme}` === "dark" ? "#13c2c299" : "#13c2c2")};
`

const CardWrapper = styled(Card)`
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 4;
	width: auto;
	border-radius: 20px;
	box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
`

const CardContent = styled.div`
	width: 360px;
	@media (max-width: 640px) {
		width: 420px;
	}
`

const CardHeader = styled.header`
	display: flex;
	align-items: center;
	justify-content: space-between;
`

const Logo = styled(Image)`
	font-size: 64px;
	filter: invert(71%) sepia(63%) saturate(2220%) hue-rotate(128deg) brightness(89%) contrast(85%);
`

const GradientText = styled.span`
	font-size: 28px;
	text-align: center;
	background: -webkit-linear-gradient(left, #13c2c2, #13c2c299);
	background-clip: text;
	-webkit-background-clip: text;
	-webkit-text-fill-color: transparent;
`

const ThemeButton = styled(Button)`
	border: none;
`

const FormWrapper = styled.main`
	padding-top: 48px;

	/* Change Autocomplete styles in Chrome*/
	input:-webkit-autofill,
	input:-webkit-autofill:hover,
	input:-webkit-autofill:focus {
		-webkit-text-fill-color: ${({ theme }) => (`${theme}` === "dark" ? "white" : "black")};
		-webkit-box-shadow: 0 0 0px 1000px ${({ theme }) => (`${theme}` === "dark" ? "black" : "white")} inset;
		transition: background-color 5000s ease-in-out 0s;
	}
`

const SubmitButton = styled(Button)`
	width: 100%;
	border-radius: 20px !important;
	color: ${({ theme }) => (`${theme}` === "dark" ? "black" : "white")};
`

const LoginForm: FC = () => {
	const theme = useSelector((state: { global: globalStateType }) => state.global.theme)
	const dispatch = useDispatch()
	const { newFormat } = useLocale()

	const setTheme = () => {
		dispatch(
			setGlobalState({
				theme: theme === "dark" ? "light" : "dark"
			})
		)
	}

	const rules: FormRules = {
		username: [
			{
				required: true
			}
		],
		password: [
			{
				required: true
			}
		],
		googleAuthCode: [
			{
				required: true,
				max: 6
			}
		],
		merchantCode: []
	}
	const navigate = useNavigate()

	const onFinished = async (form: LoginParams) => {
		dispatch(setLoad(true))
		const res = await dispatch(
			await loginAsync({
				...form,
				password: md5ToString(form.username.trim() + form.password.trim()),
				merchantCode: "DXZK",
				type: 1
			})
		)
		if (res) {
			navigate("/")
			await dispatch(await getPermissionsAsync())
			await dispatch(await getCurrencyInfoAsync())
			await dispatch(await initAsync())
		}
		dispatch(setLoad(false))
	}

	return (
		<Wrapper className="login-page" theme={theme}>
			<CardWrapper>
				<CardContent>
					<CardHeader>
						<Logo src={logo} preview={false} />
						<GradientText>{newFormat({ id: "tips.title" })}</GradientText>
						<Tooltip title={newFormat({ id: "tips.theme" })}>
							<ThemeButton
								shape="default"
								icon={theme === "dark" ? <MoonOutlined /> : <SunOutlined />}
								onClick={() => setTheme()}
							/>
						</Tooltip>
					</CardHeader>
					<FormWrapper theme={theme}>
						<Form size="large" onFinish={onFinished} initialValues={{ merchantCode: "DXZK" }}>
							<Form.Item<FieldType> name="username" rules={rules.username}>
								<Input addonBefore={<UserOutlined />} placeholder={newFormat({ id: "tips.usernamePlaceholder" })} />
							</Form.Item>
							<Form.Item<FieldType> name="password" rules={rules.password}>
								<Input.Password addonBefore={<LockOutlined />} placeholder={newFormat({ id: "tips.passwordPlaceholder" })} />
							</Form.Item>
							<Form.Item<FieldType> name="googleAuthCode" rules={rules.googleAuthCode}>
								<Input addonBefore={<CheckSquareOutlined />} placeholder={newFormat({ id: "tips.googleAuthCodePlaceholder" })} />
							</Form.Item>
							<Form.Item<FieldType> name="merchantCode">
								<Input addonBefore={<CheckCircleOutlined />} placeholder={newFormat({ id: "tips.merchantCodePlaceholder" })} />
							</Form.Item>
							<Form.Item>
								<SubmitButton type="primary" htmlType="submit" theme={theme}>
									{newFormat({ id: "tips.confirm" })}
								</SubmitButton>
							</Form.Item>
						</Form>
					</FormWrapper>
				</CardContent>
			</CardWrapper>
		</Wrapper>
	)
}

export default LoginForm
